#!/bin/bash
#
# Description: Create a staging directorie per slide
# 
# The MIT License (MIT)
# Copyright (c) 2014-2016, Bas G.L. Nelissen, UMC Utrecht, the Netherlands.
# 
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
# 
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# 

# Variables
SCRIPTNAME="$(basename $0)"
DESCRIPTIONSHORT="Create a staging directory per slide."
DEPENDENCIES=()

# Errors go to stderr
err() {
  echo "${SCRIPTNAME} ERROR: $@" >&2
}

# usage message
usage() {
cat <<- EOF
$SCRIPTNAME --help for more information.
EOF
}

# version info
version() {
cat << EOF
slideToolkit 0.2 beta
($SCRIPTNAME is part of the slideToolkit)

The MIT License (MIT) <http://opensource.org/licenses/MIT>
Copyright (c) 2014-2016, Bas G.L. Nelissen, UMC Utrecht, the Netherlands.

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

There is NO WARRANTY, to the extent permitted by law.

Written by Bas G.L. Nelissen | https://github.com/bglnelissen.
EOF
}


# help message
helpMessage() {
cat <<- EOF
${SCRIPTNAME}: ${DESCRIPTIONSHORT}

usage:
  $SCRIPTNAME -f <filename> 

options:
  -f, --file <filename>     Move file into a similar named directory 

  [--ignore-dependencies]   ignores all dependencies, but gives warning

  --help                    display this help
  --version                 display version and license information

examples:
  $SCRIPTNAME "file.tif"
  $SCRIPTNAME  --file="file.tif"

print a job list:

  find "\$(pwd)" -iname "*.TIF" -exec $(command -v "$SCRIPTNAME") -f "{}" \;


dependencies: ${DEPENDENCIES[@]}

Move file into a similar named directory at the same location. Pipe the
'job list' output in 'parallel' for parallel processing.

The slideToolkit and all its tools are released under the terms of the MIT license.
The slideToolkit (C) 2014-2016, Bas G.L. Nelissen, UMC Utrecht, the Netherlands.
Report issues at https://github.com/bglnelissen/slideToolkit/issues.

EOF
}

# Menu
# Empty variables
FILE=""
# illegal option
illegalOption() {
cat <<- EOF
$SCRIPTNAME: illegal option $1
$(usage)
EOF
exit 1
}
# loop through options
while :
do
  case $1 in
    --help | -\?)
      helpMessage
      exit 0 ;;
    --version )
      version
      exit 0 ;;
    -f | --file)
      FILE=$2
      shift 2 ;;
    --file=*)
      FILE=${1#*=}
      shift ;;
     --ignore-dependencies)
      IGNOREDEPENDENCIES=TRUE
      shift ;;
    --) # End of all options
      shift
      break ;;
    -*)
      illegalOption "$1"
      shift ;;
    *)  # no more options. Stop while loop
      break ;;
  esac
done
# Defaults
# set FILE
if [ "$FILE" != "" ]; then
  FILE="$FILE"
else
  FILE="$1"
fi
# set IGNOREDEPENDENCIES
if [[ "$IGNOREDEPENDENCIES" =~ (true|TRUE|YES|yes) ]] ; then
  IGNOREDEPENDENCIES=true
else
  IGNOREDEPENDENCIES=false
fi

# requirements
checkRequirements() {
  if ! [[ -f "$FILE" ]] ; then
    err "No such file: $FILE"
    usage
    exit 1
  fi
}

# Dependencies
checkDependencies(){
  DEPS=""
  DEPS_FAIL="0"
  for DEP in ${DEPENDENCIES[@]}; do
    if [[ 0 != "$(command -v "$DEP" >/dev/null ;echo "$?")" ]]; then
       err "Missing dependency: $DEP"
       DEPS_FAIL=$(($DEPS_FAIL + 1))
    fi
  done
  if [[ "$DEPS_FAIL" > 0 ]]; then
    # only warning when --ignore-dependencies is set.
    if [[ "$IGNOREDEPENDENCIES" == "true" ]]; then
      err "Ignoring missing dependencies (${DEPS_FAIL}), continue..."
    else
      err "Fix missing dependencies (${DEPS_FAIL}), exit."
      usage
      exit 1
    fi
  fi
}

# actual program
programOutput(){
  FILEFULL="$(echo "$(cd "$(dirname "$FILE")"; pwd)"/"$(basename "$FILE")")" # full path $FULL
  BASENAME="$(basename "$FILEFULL")"    # basename
  EXTENSION="${BASENAME##*.}"         # extension
  FILEPATH="${FILEFULL%.*}"           # full path, no extension
  FILENAME="${BASENAME%.*}"           # filename, no extension"
  mkdir -p "$FILEPATH"
  mv "$FILE" "$FILEPATH"/
}

# all check?
checkRequirements
checkDependencies

# lets go!
programOutput